package dao

import (
	"context"

	"gorm.io/gorm/clause"

	"open/internal/model"
)

// GetAppVersion 获取版本信息
func (d *Dao) GetAppVersion(ctx context.Context, appID string, platform int32) (*model.MiniAppVersion, error) {
	version := new(model.MiniAppVersion)
	err := d.db.WithContext(ctx).Where("app_id = ? and platform = ?", appID, platform).First(version).Error
	return version, err
}

// LockAppVersion 获取版本信息
func (d *Dao) LockAppVersion(ctx context.Context, appID string, platform int32) (*model.MiniAppVersion, error) {
	version := new(model.MiniAppVersion)
	err := d.db.WithContext(ctx).
		Clauses(clause.Locking{Strength: "UPDATE"}).
		Where("app_id = ? and platform = ?", appID, platform).
		First(version).Error
	return version, err
}

// CreateAppVersion 新建app版本
func (d *Dao) CreateAppVersion(ctx context.Context, version *model.MiniAppVersion) error {
	return d.FromContext(ctx).Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "platform"}, {Name: "app_id"}},
		UpdateAll: true,
	}).Create(version).Error
}

// VersionLogs 获取版本日志
func (d *Dao) VersionLogs(ctx context.Context, versionID int64, pageNum, pageSize int32) (logs []*model.MiniAppVersionLog, err error) {
	db := d.FromContext(ctx).Where("version_id = ?", versionID)
	err = db.Offset(int((pageNum - 1) * pageSize)).Limit(int(pageSize)).Find(&logs).Error
	return
}

// SaveAppVersion 保存app版本信息
func (d *Dao) SaveAppVersion(ctx context.Context, appVersion *model.MiniAppVersion) error {
	return d.FromContext(ctx).Save(appVersion).Error
}

// CreateVersionLog 创建版本记录
func (d *Dao) CreateVersionLog(ctx context.Context, log *model.MiniAppVersionLog) error {
	return d.FromContext(ctx).Create(log).Error
}
